// JavaScript source code



/**
 * Json对象操作，增删改查
 *
 * @author  lellansin
 * @blog    www.lellansin.com
 * @version 0.1
 * 
 * 解决一些常见的问题
 * get/set 解决获取和设置时，无节点中断的问题
 * create  可以创建多级节点，若存在则覆盖新值
 * delete  删除节点及其子节点
 * print_r 格式化输出对象（调试用）
 * 实例见底部
 */

function Json() {

}

/**
 * 获取Json对象中的某个节点
 * 例如：json.get(Data, 'country', 'province', 'city');
 * 结果则返回 Data['country']['province']['city']
 * 无则返回false
 */
Json.prototype.get = function (obj, key) {
    var args = this.get.arguments;
    // // console.log(this);  Json{}
    // // console.log(this.get); 就是此方法
    // // console.log(args);  arguments 实参     args实参的个数
    var result = obj;

    for (var i = 1; i < args.length; i++) {
        result = result[args[i]];
        if (result === undefined) {
            return false;
        };
    };
     return result;
};

/**
 * 设置Json对象中的某个节点
 * 例如：obj.set(data, "ENTRY", "FA_TOKEN_INVALID", 1234);
 * 将 data['ENTRY']['FA_TOKEN_INVALID'] 设置为1234
 * 成功true, 失败false
 */
Json.prototype.set = function (obj, key) {
    var args = this.set.arguments;
    if (ergodic_set(obj, args, 1)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 在Json对象中创建节点(若存在则覆盖值)
 * 例如：obj.create(data, 'add', 'hello', 'test', 120);
 * 添加 data['create']['hello']['test'] 节点并设置值为 120
 * 成功true, 失败false
 */
Json.prototype.create = function (obj, key) {
    var args = this.create.arguments;
    if (ergodic_create(obj, args, 1)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 在Json对象中删除节点
 * 例如：obj.delete(prods, 'grade', 'math');
 * 成功true, 失败false
 */
Json.prototype.delete = function (obj,key) {
    var args = this.delete.arguments;
    if (ergodic_delete(obj, args, 1)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 返回Json对象的字符串形式（封装 ECMAScript 库函数）
 */
Json.prototype.getStr = function (obj) {
    return JSON.stringify(obj);
}

/**
 * 解析字符串返回Json对象（封装 ECMAScript 库函数）
 */
Json.prototype.getJson = function (str) {
    return JSON.parse(str);
}

/**
 * 格式化输出Json对象
 */
Json.prototype.print_r = function (obj) {
    // console.log("{")
    ergodic_print(obj, "");
    // console.log("}")
}

function ergodic_print(obj, indentation) {
    var indent = "  " + indentation;
    if (obj.constructor == Object) {
        for (var p in obj) {
            if (obj[p].constructor == Array || obj[p].constructor == Object) {
                // console.log(indent + "[" + p + "] => " + typeof (obj) + "");
                // console.log(indent + "{");
                ergodic_print(obj[p], indent);
                // console.log(indent + "}");
            } else if (obj[p].constructor == String) {
                // console.log(indent + "[" + p + "] => '" + obj[p] + "'");
            } else {
                // console.log(indent + "[" + p + "] => " + obj[p] + "");
            }
        }
    }
}

function ergodic_set(obj, args, floor) {
    if (obj.constructor == Object) {
        for (var tmpKey in obj) {
            if (tmpKey == args[floor]) {
                if (floor < args.length - 2) {
                    return ergodic_set(obj[tmpKey], args, floor + 1);
                } else {
                    // 此时参数floor为倒数第二个，加1值为最后一个
                    obj[tmpKey] = args[floor + 1];
                    // console.log("成功设置，返回true");
                    return true;
                }
            }
        }
    }
}

function ergodic_create(obj, args, floor) {
    if (obj.constructor == Object) {
        for (var tmpKey in obj) {
            if (tmpKey == args[floor]) {
                if (floor < args.length - 2) {
                    return ergodic_create(obj[tmpKey], args, floor + 1);
                } else {
                    obj[tmpKey] = args[floor + 1];
                    return true;
                }
            }
        }
    }
    // 节点不存在，创建新节点
    if (floor < args.length - 1) {
        var jsonstr = getJsonFormat(args[args.length - 1]);

        for (var i = args.length - 2; i > floor; i--) {
            jsonstr = '{"' + args[i] + '":' + jsonstr + '}';
        };

        // 使用eval解析第三方Json数据时，可能会执行恶意代码
        // var node = eval('(' + jsonstr + ')');
        var node = JSON.parse(jsonstr);
        obj[args[floor]] = node;
        return true;
    }
}

function ergodic_delete(obj, args, floor) {
    if (obj.constructor == Object) {
        for (var tmpKey in obj) {
            if (tmpKey == args[floor]) {
                if (floor < args.length - 1) {
                    return ergodic_delete(obj[tmpKey], args, floor + 1);
                } else {
                    delete obj[tmpKey];
                    return true;
                }
            }
        }
    }
}


function getJsonFormat(param) {
    if (param.constructor == String) {
        return '"' + param + '"';
    } else {
        return param;
    }
}



/**
 * 使用实例
 */

var data = {
    OK: 200,
    FAIL: 500,
    ENTRY: {
        FA_TOKEN_INVALID: 1001,
        FA_TOKEN_EXPIRE: 1002,
        FA_USER_NOT_EXIST: 1003
    },
    GATE: {
        FA_NO_SERVER_AVAILABLE: 2001
    },
    CHAT: {
        FA_CHANNEL_CREATE: 3001,
        FA_CHANNEL_NOT_EXIST: 3002,
        FA_UNKNOWN_CONNECTOR: 3003,
        FA_USER_NOT_ONLINE: 3004
    }
};

var json = new Json();
//路段对象，包含开始，结束桩号，路段名字，路段方向，路段长度



//roadid  路线ID
//zh  桩号
//fx  路线方向
// 调用示例 findRoad('{8A8642E4-4901-4E4B-9BC7-179266BB5E25}', 1658, '上行')
function findRoad(roadid, zh, fx) {
    var ldobject =
{
    "kszh": 0,
    "jszh": 0,
    "name": "",
    "fx": "",
    "len": 0
};
    
    fx = fx.replace('方向', '');

    var jo1 = json.get(RoadIDObjects,roadid);
    var jo = json.get(jo1,fx); 

    for (var key in jo) {
        if (fx.replace('上行','') != fx) {
            if ((jo[key].kszh <= zh) && (jo[key].jszh >= zh)) {
                ldobject.kszh = jo[key].kszh;
                ldobject.jszh = jo[key].jszh;
                ldobject.name = key;
                ldobject.fx = fx;
                ldobject.len = Math.abs(ldobject.kszh - ldobject.jszh);
                break;
            }
        } else {
            if ((jo[key].kszh <= zh) && (jo[key].jszh >= zh)) {
                ldobject.kszh = jo[key].kszh;
                ldobject.jszh = jo[key].jszh;
                ldobject.name = key;
                ldobject.fx = fx;
                break;
            }
        }

    };
    return ldobject;
}




//获取URL参数值
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
}


function base64_encode(str) {
    if (window.btoa) // Internet Explorer 10 and above  
        return window.btoa(unescape(encodeURIComponent(str)));
    else {
        // Cross-Browser Method (compressed)  

        // Create Base64 Object  
        var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } }
        // Encode the String  
        return Base64.encode(unescape(encodeURIComponent(str)));
    }
}

function base64_decode(str) {
    if (window.atob) // Internet Explorer 10 and above  
        return decodeURIComponent(escape(window.atob(str)));
    else {
        // Cross-Browser Method (compressed)  

        // Create Base64 Object  
        var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } }
        // Encode the String  
        return decodeURIComponent(escape(Base64.decode(str)));
    }
}


//json使用方法
//var jsonObj2 = {
//    teacher: [
//          { name: "jordan", sex: "m", age: "40" },
//          { name: "bryant", sex: "m", age: "28" },
//          { name: "McGrady", sex: "m", age: "27" }
//    ]
//};

//var jsonObj2New = {};
//$("#btn").click(function () {
//    //invoke the update
//    updateData("jordan");
//    var persons = jsonObj2.teacher;
//    for (var i = 0; i < persons.length; i++) {
//        var cur_person = persons[i];
//        alert(cur_person.sex);
//    }

//    //invoke the delete
//    deleteData("jordan");
//    var persons = jsonObj2.teacher;
//    for (var i = 0; i < persons.length; i++) {
//        var cur_person = persons[i];
//        alert(cur_person.sex);
//    }

//    //push 
//    var temp = { name: "kenny", sex: "m", age: "25" };
//    jsonObj2.teacher.push(temp);

//    var persons = jsonObj2.teacher;
//    for (var i = 0; i < persons.length; i++) {
//        var cur_person = persons[i];
//        alert(cur_person.name);
//    }

//});

//function updateData(name) {
//    var persons = jsonObj2.teacher;
//    //alert(name);
//    for (var i = 0; i < persons.length; i++) {
//        var cur_person = persons[i];
//        if (cur_person.name == name) {
//            persons[i].sex = "f";
//        }
//    }
//}

//function deleteData(name) {
//    var persons = jsonObj2.teacher;
//    //alert(name);
//    for (var i = 0; i < persons.length; i++) {
//        var cur_person = persons[i];
//        if (cur_person.name == name) {
//            jsonObj2.teacher.splice(i, 1);
//        }
//    }
//}